package com.airline.dao;

import com.airline.entity.Order;
import com.airline.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class OrderDAO {

    /**
     * 新增订单（订票时调用，返回自增订单号）
     */
    public void addOrder(Order order) {
        String sql = "INSERT INTO `order` (flight_no, user_name, book_time) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setString(1, order.getFlightNo());
            pstmt.setString(2, order.getUserName());
            pstmt.setObject(3, order.getBookTime());
            pstmt.executeUpdate();

            // 获取自增订单号并回写至Order对象
            ResultSet rs = pstmt.getGeneratedKeys();
            if (rs.next()) {
                order.setId(rs.getInt(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据订单号查询订单（退票时调用）
     */
    public Order findOrderById(int orderId) {
        Order order = null;
        String sql = "SELECT * FROM `order` WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, orderId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                order = buildOrderFromResultSet(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return order;
    }

    /**
     * 根据用户名查询订单（查询个人订单时调用）
     */
    public List<Order> findOrdersByUserName(String userName) {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM `order` WHERE user_name = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, userName);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                Order order = buildOrderFromResultSet(rs);
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }

    /**
     * 工具方法：从ResultSet封装Order对象（复用代码）
     */
    private Order buildOrderFromResultSet(ResultSet rs) throws SQLException {
        Order order = new Order();
        order.setId(rs.getInt("id"));
        order.setFlightNo(rs.getString("flight_no"));
        order.setUserName(rs.getString("user_name"));
        order.setBookTime(rs.getObject("book_time", LocalDateTime.class));
        return order;
    }
}
